<?php


namespace Ffzhou\HydrophisLogin\Extend;


use Exception;

/**
 * FieldFlint操作类
 * Class FieldFlint
 * @package Zhouweijiebest\HydrophisLogin\Extend
 */
class FieldFlint
{
    const LOGIN_PROVIDER = 'hydrophis_user';

    /**
     * 登录FieldFlint接口
     * @param string $url 接口
     * @param string $username 用户名
     * @param string $password 密码
     * @return array|null
     */
    public function login($url, $username, $password) {
        try {
            return $this->http($url, ['username' => $username, 'password' => $password], 'POST');
        }
        catch (Exception $exception) {
            return null;
        }
    }

    /**
     * 根据token获取用户信息
     * @param string $url 接口
     * @param string $token Token
     * @return array|null
     */
    public function get($url, $token) {
        try {
            return $this->http($url, ['token' => $token], 'POST');
        }
        catch (Exception $exception) {
            return null;
        }
    }

    /**
     * 发送HTTP请求方法
     * @param string $url 请求URL
     * @param array $params 请求参数
     * @param string $method 请求方法GET/POST
     * @param array $headers 请求头
     * @param bool $multi 是否上传文件
     * @param array $options 其它curl自定义数据项
     * @return array|null $data 响应数据
     * @throws Exception
     */
    protected function http($url, $params, $method='GET', $headers=[], $multi=false, $options=[])
    {
        $opts = [
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_HTTPHEADER => $headers,
        ];
        /* 根据请求类型设置特定参数 */
        switch (strtoupper($method)) {
            case 'GET':
                $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
                break;
            case 'POST':
                //判断是否传输文件 或字符串
                $params = ($multi || !is_array($params) ? $params : http_build_query($params));
                $opts[CURLOPT_URL] = $url;
                $opts[CURLOPT_POST] = 1;
                $opts[CURLOPT_POSTFIELDS] = $params;
                break;
            default:
                throw new Exception('Unsupported request mode');
        }

        foreach ($options as $key => $val) {
            $opts[$key] = $val;
        }

        // 初始化并执行curl请求
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($error)
            throw new Exception('An error occurred in the request: ' . $error);
        return json_decode($data, true);
    }
}
